package com.lingnan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingnan.entity.po.Interview;
import com.lingnan.entity.po.JobApplication;
import com.lingnan.entity.po.JobSeeker;
import com.lingnan.entity.po.Resume;
import com.lingnan.mapper.InterviewMapper;
import com.lingnan.mapper.JobApplicationMapper;
import com.lingnan.mapper.JobSeekerMapper;
import com.lingnan.mapper.ResumeMapper;
import com.lingnan.service.JobSeekerService;
import com.lingnan.utils.LoginContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
@Transactional
public class JobSeekerServiceImpl extends ServiceImpl<JobSeekerMapper, JobSeeker>
        implements JobSeekerService {
    
    @Autowired
    private ResumeMapper resumeMapper;
    
    @Autowired
    private JobApplicationMapper applicationMapper;
    
    @Autowired
    private InterviewMapper interviewMapper;
    
    @Override
    public JobSeeker createSeeker(JobSeeker seeker) {
//        String loginId = LoginContextHolder.getLoginId();
//        seeker.setUserId(Long.parseLong(loginId));
        seeker.setCreatedAt(new Date());
        save(seeker);
        return seeker;
    }
    
    @Override
    public JobSeeker updateSeeker(Long id, JobSeeker seeker) {
        JobSeeker existingSeeker = getById(id);
        if (existingSeeker == null) {
            throw new RuntimeException("求职者不存在");
        }
        
        String oldName = existingSeeker.getRealName();
        String newName = seeker.getRealName();
        
        // 更新求职者信息
        seeker.setId(id);
        updateById(seeker);
        
        // 同步更新面试记录中的求职者姓名
        if (!Objects.equals(oldName, newName)) {
            interviewMapper.updateSeekerNameBatch(oldName, newName);
        }
        
        return seeker;
    }
    
    @Override
    public boolean deleteSeeker(Long id, boolean force) {
        // 检查删除条件
        Map<String, Object> conditions = checkDeleteConditions(id);
        boolean hasApplications = (Boolean) conditions.get("hasApplications");
        boolean hasInterviews = (Boolean) conditions.get("hasInterviews");
        
        if (!force && (hasApplications || hasInterviews)) {
            throw new RuntimeException("求职者存在投递记录或面试记录，无法删除。如需强制删除，请确认操作。");
        }
        
        if (force) {
            // 强制删除：先删除面试记录，再删除投递记录，再删除简历，最后删除求职者
            deleteRelatedDataCascade(id);
        }
        
        // 删除求职者
        return removeById(id);
    }
    
    @Override
    public JobSeeker getSeekerDetail(Long id) {
        JobSeeker seeker = baseMapper.selectWithResumes(id);
        if (seeker != null) {
            // 查询投递记录
            List<JobApplication> applications = applicationMapper.selectBySeekerIdd(id);
            seeker.setApplications(applications);
        }
        return seeker;
    }
    
    @Override
    public IPage<JobSeeker> pageSeekers(Page<JobSeeker> page, String keyword) {
        LambdaQueryWrapper<JobSeeker> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(keyword)) {
            wrapper.like(JobSeeker::getRealName, keyword)
                   .or()
                   .like(JobSeeker::getJobIntent, keyword);
        }
        wrapper.orderByDesc(JobSeeker::getCreatedAt);
        return page(page, wrapper);
    }
    
    @Override
    public Map<String, Object> checkDeleteConditions(Long seekerId) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查投递记录
        int applicationCount = baseMapper.countApplicationsBySeekerIdd(seekerId);
        result.put("hasApplications", applicationCount > 0);
        result.put("applicationCount", applicationCount);
        
        // 检查面试记录
        int interviewCount = baseMapper.countInterviewsBySeekerIdd(seekerId);
        result.put("hasInterviews", interviewCount > 0);
        result.put("interviewCount", interviewCount);
        
        // 检查简历数量
        LambdaQueryWrapper<Resume> resumeWrapper = new LambdaQueryWrapper<>();
        resumeWrapper.eq(Resume::getSeekerId, seekerId);
        long resumeCount = resumeMapper.selectCount(resumeWrapper);
        result.put("resumeCount", resumeCount);
        
        return result;
    }
    
    /**
     * 级联删除相关数据
     */
    private void deleteRelatedDataCascade(Long seekerId) {
        // 1. 获取投递记录
        List<JobApplication> applications = applicationMapper.selectBySeekerIdd(seekerId);
        
        // 2. 删除面试记录
        for (JobApplication app : applications) {
            LambdaQueryWrapper<Interview> interviewWrapper = new LambdaQueryWrapper<>();
            interviewWrapper.eq(Interview::getApplicationId, app.getId());
            interviewMapper.delete(interviewWrapper);
        }
        
        // 3. 删除投递记录
        LambdaQueryWrapper<JobApplication> appWrapper = new LambdaQueryWrapper<>();
        appWrapper.eq(JobApplication::getSeekerId, seekerId);
        applicationMapper.delete(appWrapper);
        
        // 4. 删除简历
        LambdaQueryWrapper<Resume> resumeWrapper = new LambdaQueryWrapper<>();
        resumeWrapper.eq(Resume::getSeekerId, seekerId);
        resumeMapper.delete(resumeWrapper);
    }
}